#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
RAG智能对话机器人 - 命令行界面
基于您的Milvus文件索引和本地Ollama模型
"""

import sys
import time
from datetime import datetime
from tools.RAGChatBot import RAGChatBot


class RAGChatInterface:
    """RAG对话界面"""
    
    def __init__(self):
        self.bot = None
        self.running = True
    
    def print_header(self):
        """打印头部信息"""
        print("=" * 80)
        print("🤖 RAG智能文件助手")
        print("基于您的文件内容进行智能问答")
        print("=" * 80)
    
    def print_help(self):
        """打印帮助信息"""
        help_text = """
💡 可用命令:
   /help     - 显示帮助信息
   /models   - 查看可用模型
   /model    - 切换模型 (如: /model llama3.2:latest)
   /config   - 查看当前配置
   /history  - 查看对话历史
   /clear    - 清空对话历史
   /stats    - 查看统计信息
   /quit     - 退出程序

💬 直接输入问题开始对话，例如：
   - "帮我找找Python相关的文件"
   - "有哪些配置文件？"
   - "最近修改的文档有什么？"
        """
        print(help_text)
    
    def initialize_bot(self) -> bool:
        """初始化机器人"""
        print("🚀 正在初始化RAG智能助手...")
        
        # 获取用户配置
        print("\n📝 配置RAG系统:")
        
        # Ollama URL
        default_ollama = "http://172.26.32.1:11434"
        ollama_url = input(f"Ollama服务地址 (回车使用默认: {default_ollama}): ").strip()
        if not ollama_url:
            ollama_url = default_ollama
        
        # Milvus集合
        default_collection = "workspace_files"
        collection = input(f"Milvus集合名称 (回车使用默认: {default_collection}): ").strip()
        if not collection:
            collection = default_collection
        
        # 创建机器人
        try:
            self.bot = RAGChatBot(
                ollama_url=ollama_url,
                milvus_collection=collection
            )
            
            # 初始化
            if not self.bot.initialize():
                print("❌ 初始化失败")
                return False
            
            return True
            
        except Exception as e:
            print(f"❌ 创建RAG机器人失败: {e}")
            return False
    
    def handle_command(self, command: str) -> bool:
        """处理命令"""
        command = command.lower().strip()
        
        if command == "/help":
            self.print_help()
        
        elif command == "/models":
            models = self.bot.get_available_models()
            print(f"\n📋 可用模型 ({len(models)}个):")
            for i, model in enumerate(models, 1):
                current = " (当前)" if model == self.bot.current_model else ""
                print(f"   {i}. {model}{current}")
        
        elif command.startswith("/model"):
            parts = command.split(None, 1)
            if len(parts) > 1:
                model_name = parts[1]
                self.bot.switch_model(model_name)
            else:
                print("❌ 请指定模型名称，如: /model llama3.2:latest")
        
        elif command == "/config":
            stats = self.bot.get_stats()
            print(f"\n⚙️ 当前配置:")
            print(f"   当前模型: {stats['current_model']}")
            print(f"   最大检索文件数: {stats['config']['max_context_files']}")
            print(f"   最大上下文长度: {stats['config']['max_context_length']}")
            print(f"   相似度阈值: {stats['config']['similarity_threshold']}")
        
        elif command == "/history":
            history = self.bot.get_chat_history()
            if not history:
                print("📝 暂无对话历史")
            else:
                print(f"\n📝 对话历史 ({len(history)}条消息):")
                for msg in history[-10:]:  # 只显示最近10条
                    time_str = datetime.fromtimestamp(msg.timestamp).strftime("%H:%M:%S")
                    role = "👤" if msg.role == "user" else "🤖"
                    content = msg.content[:100] + "..." if len(msg.content) > 100 else msg.content
                    print(f"   [{time_str}] {role}: {content}")
        
        elif command == "/clear":
            self.bot.clear_history()
        
        elif command == "/stats":
            stats = self.bot.get_stats()
            print(f"\n📊 系统统计:")
            print(f"   对话消息数: {stats['chat_messages']}")
            print(f"   文件索引数: {stats['milvus_entities']:,}")
            print(f"   当前模型: {stats['current_model']}")
        
        elif command == "/quit":
            print("👋 再见！")
            return False
        
        else:
            print("❌ 未知命令，输入 /help 查看帮助")
        
        return True
    
    def format_response(self, response: str, sources: list):
        """格式化响应"""
        print("\n🤖 助手回答:")
        print("-" * 60)
        print(response)
        
        if sources:
            print(f"\n📚 参考文件 ({len(sources)}个):")
            for i, source in enumerate(sources, 1):
                print(f"   {i}. {source['file_name']}")
                print(f"      路径: {source['file_path']}")
                print(f"      相似度: {source['similarity_score']:.3f}")
                if i < len(sources):
                    print()
    
    def chat_loop(self):
        """主对话循环"""
        print("\n💬 开始对话 (输入 /help 查看命令):")
        print("-" * 60)
        
        while self.running:
            try:
                # 获取用户输入
                user_input = input("\n👤 您: ").strip()
                
                if not user_input:
                    continue
                
                # 处理命令
                if user_input.startswith('/'):
                    if not self.handle_command(user_input):
                        break
                    continue
                
                # 处理普通对话
                print("🔍 正在思考...")
                start_time = time.time()
                
                try:
                    response, sources = self.bot.chat(user_input)
                    elapsed = time.time() - start_time
                    
                    self.format_response(response, sources)
                    print(f"\n⏱️ 处理耗时: {elapsed:.2f}秒")
                    
                except KeyboardInterrupt:
                    print("\n⏹️ 处理已中断")
                    continue
                    
            except KeyboardInterrupt:
                print("\n\n👋 收到中断信号，正在退出...")
                break
            except Exception as e:
                print(f"❌ 处理出错: {e}")
                continue
    
    def run(self):
        """运行对话界面"""
        self.print_header()
        
        if not self.initialize_bot():
            print("❌ 初始化失败，程序退出")
            return
        
        try:
            self.chat_loop()
        except Exception as e:
            print(f"❌ 程序运行出错: {e}")
        finally:
            print("\n🔚 程序结束")


def main():
    """主函数"""
    try:
        interface = RAGChatInterface()
        interface.run()
    except KeyboardInterrupt:
        print("\n👋 程序被中断")
    except Exception as e:
        print(f"❌ 程序异常: {e}")


if __name__ == "__main__":
    main()